package com.gin.no_gay_alliance.database.manager;

import androidx.annotation.NonNull;

import com.gin.jackson.utils.ObjectUtils;
import com.gin.nga.response.body.ReadBody;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.database.dao.ReplyHistoryDao;
import com.gin.no_gay_alliance.database.entity.ReplyHistory;
import com.gin.no_gay_alliance.database.entity.ReplyHistoryTopic;
import com.gin.no_gay_alliance.database.where.ReplyHistoryWhere;
import com.gin.no_gay_alliance.utils.DataStoreUtils;
import com.gin.no_gay_alliance.viewmodel.PageData;
import com.gin.no_gay_alliance.viewmodel.ReadItem;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

/**
 * 回复历史管理器
 *
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/16 14:51
 **/
public class ReplyHistoryManager {
    private static final String TAG = ReplyHistoryManager.class.getSimpleName();
    /**
     * 运行模式保存的key
     */
    private static final String DATA_STORE_KEY_REPLY_HISTORY_MODE = "REPLY_HISTORY_MODE";

    /**
     * 记录一组回复历史
     *
     * @param replyHistoryTopic 观察主题
     * @param replyHistories    回复历史
     */
    public static void record(@NonNull ReplyHistoryTopic replyHistoryTopic, @NonNull List<ReplyHistory> replyHistories) {
        // 如果属于观察主题，更新信息
        boolean isObservedTopic = isObservedTopic(replyHistoryTopic.topicId);
        if (isObservedTopic) {
            addObservedTopic(replyHistoryTopic);
        }
        if (!ObjectUtils.isEmpty(replyHistories)) {
            // 根据当前运行模式，决定是否记录回复历史
            switch (getMode()) {
                case NORMAL:
                    if (isObservedTopic) {
                        addReplyHistories(replyHistories);
                    }
                    break;
                case HISTORY:
                    addReplyHistories(replyHistories);
                    break;
                case CLOSED:
                    // 关闭状态，不记录
                    break;
            }
        }
    }

    /**
     * 搜索符合条件的历史回复
     *
     * @param replyHistoryWhere 查询条件
     * @param page
     * @return
     */
    public static PageData<ReplyHistory> page(ReplyHistoryWhere replyHistoryWhere, int page) {
        int size = 20;
        ReplyHistoryDao dao = MyApplication.app.ngaDatabase.replyHistoryDao();
        // 总条数
        int count = dao.count(replyHistoryWhere.buildSql("select count(1) from ReplyHistory where %s "));
        // limit
        String limit = String.format(Locale.CHINA, " limit %d,%d", (page - 1) * size, size);
        // 回复历史
        List<ReplyHistory> list = dao.list(replyHistoryWhere.buildSql("select * from ReplyHistory where %s order by uuid desc" + limit));
        return new PageData<>(list, page, size, count);
    }


    /**
     * 获取当前运行模式
     *
     * @return 运行模式
     */
    public static Mode getMode() {
        return Mode.findByOrdinal(DataStoreUtils.getInstance().get(DATA_STORE_KEY_REPLY_HISTORY_MODE, Mode.NORMAL.ordinal()));
    }

    /**
     * 设置运行模式
     *
     * @param mode 运行模式
     */
    public static void setMode(Mode mode) {
        DataStoreUtils.getInstance().set(DATA_STORE_KEY_REPLY_HISTORY_MODE, mode.ordinal());
    }

    /**
     * 添加一个主题为观察主题
     *
     * @param replyHistoryTopic 观察主题
     */
    public static void addObservedTopic(ReplyHistoryTopic replyHistoryTopic) {
        MyApplication.app.ngaDatabase.replyHistoryTopicDao().add(replyHistoryTopic);
    }

    /**
     * 查询所有观察主题
     *
     * @return 所有观察主题
     */
    public static List<ReplyHistoryTopic> listObservedTopic() {
        return MyApplication.app.ngaDatabase.replyHistoryTopicDao().listAll();
    }

    /**
     * 查询一个主题是否为观察主题
     *
     * @param topicId 主题id
     * @return 是否为观察主题
     */
    public static boolean isObservedTopic(long topicId) {
        return MyApplication.app.ngaDatabase.replyHistoryTopicDao().get(topicId) != null;
    }

    /**
     * 移除一个观察主题
     *
     * @param topicId 主题id
     */
    public static void removeObservedTopic(long topicId) {
        MyApplication.app.ngaDatabase.replyHistoryTopicDao().remove(topicId);
    }

    /**
     * 记录一组回复历史
     *
     * @param replyHistories 回复历史
     */
    public static void addReplyHistories(@NonNull List<ReplyHistory> replyHistories) {
        MyApplication.app.ngaDatabase.replyHistoryDao().add(replyHistories);
    }

    /**
     * 记录一组回复历史
     *
     * @param body 响应
     */
    public static void addReplyHistories(@NonNull ReadBody body) {
        ReadItem readItem = new ReadItem(body);
        List<ReplyHistory> replyHistories = readItem.replyItems.stream()
                .filter(i -> i.replyId != null)
                .filter(i -> i.topicId != null)
                .map(ReplyHistory::new).collect(Collectors.toList());
        addReplyHistories(replyHistories);
    }

    /**
     * 运行模式, 使用 ordinal 值作为唯一标记，如果增加模式，只能往后增加，不能修改顺序
     */
    public enum Mode {
        /**
         * 常规模式，当主题为观察主题时才记录
         */
        NORMAL,
        /**
         * 历史模式，记录所有看到的回复
         */
        HISTORY,
        /**
         * 关闭
         */
        CLOSED,
        ;

        public static Mode findByOrdinal(int ordinal) {
            return Arrays.stream(values()).filter(i -> i.ordinal() == ordinal).findFirst().orElse(null);
        }
    }
}
